﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Hydra.Contract;

namespace Hydra.Reciever
{
    [ServiceBehavior(
        IncludeExceptionDetailInFaults = true,
        InstanceContextMode = InstanceContextMode.Single,
        ConcurrencyMode = ConcurrencyMode.Multiple)]
    class HydraService : IHydraService, IHydraCallback
    {
        IDictionary<string, OperationContext> listeners = new Dictionary<string, OperationContext>();

        public void WriteLog(LogLevel level, string message)
        {
            Console.WriteLine("Client said: " + message);
        }

        public void RegisterListener()
        {
            listeners.Add(OperationContext.Current.SessionId, OperationContext.Current);

            Console.WriteLine("SessionID:" + OperationContext.Current.SessionId);
            Console.WriteLine("Register listener. Client Count:" + listeners.Count.ToString());
        }

        public void UnregisterListener()
        {
            listeners.Remove(OperationContext.Current.SessionId);
            
            Console.WriteLine("SessionID:" + OperationContext.Current.SessionId);
            Console.WriteLine("Unregister listener. Client Count:" + listeners.Count.ToString());
        }

        #region BroadCast

        public void WriteLog(string message)
        {
            List<string> errorClints = new List<string>();

            foreach (KeyValuePair<string, OperationContext> listener in listeners)
            {
                try
                {
                    var proxy = listener.Value.GetCallbackChannel<IHydraCallback>();
                    proxy.WriteLog(message);
                }
                catch (System.Exception e)
                {
                    errorClints.Add(listener.Key);
                    Console.WriteLine("BROAD EVENT ERROR:" + e.Message);
                }
            }

            foreach (string id in errorClints)
            {
                listeners.Remove(id);
            }
        }

        public void RunTask(string parameter)
        {
            List<string> errorClints = new List<string>();

            foreach (KeyValuePair<string, OperationContext> listener in listeners)
            {
                try
                {
                    var proxy = listener.Value.GetCallbackChannel<IHydraCallback>();
                    proxy.RunTask(parameter);
                }
                catch (System.Exception e)
                {
                    errorClints.Add(listener.Key);
                    Console.WriteLine("BROAD EVENT ERROR:" + e.Message);
                }
            }

            foreach (string id in errorClints)
            {
                listeners.Remove(id);
            }
        }

        #endregion
    }
}
